package cn.itcast.com.network.udp.vv;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class ReceiveTask implements Runnable {
    private DatagramSocket receiveSocket;

    public ReceiveTask(DatagramSocket receiveSocket) {
        this.receiveSocket = receiveSocket;
    }

    @Override
    public void run() {
        //创建一个byte[]
        byte[] bytes = new byte[1024];
        DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
        try {
            while (true) {

                receiveSocket.receive(packet);
                String s = parseData(packet);
                if (s.equals("886")) {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            receiveSocket.close();
        }


    }

    //返回值用来判断是否为886从而中断进程
    private String parseData(DatagramPacket datagramPacket) {
        //输出数组
        //获得字节数组数据
        byte[] data = datagramPacket.getData();
        //获得偏移量
        int offset = datagramPacket.getOffset();
        //获得字节个数
        int length = datagramPacket.getLength();
        //通过解析获得文字
        String s = new String(data, offset, length);
        //获得发送方的ip地址
        InetAddress address = datagramPacket.getAddress();
        //获得发送方的端口号
        int port = datagramPacket.getPort();
        System.out.println("接受来自 " + address + ":" + port + "  " + s);
        return s;
    }
}
